﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ISRecord.Model.CustomeException;
using System.Data.Objects;

namespace ISRecord.Model
{
    public sealed class OutboxRepository: RepositoryBase<Outbox>
    {

        public OutboxRepository(Sender2006Entities context)
        {
            if (context == null) throw new ArgumentNullException("context");
            base.Context = context;
            
        }

        public override void Add(Outbox entity)
        {
           
            Context.Outbox.AddObject(entity);
        }

        public override void Delete(Outbox entity)
        {
            Context.Outbox.DeleteObject(entity);
        }

        public override Outbox GetByID(object id)
        {
            string no = (string)id;
            return Context.Outbox.FirstOrDefault
                (
                     x => x.OutboxNo == no
                );
        }

        public override IList<Outbox> GetAll()
        {
            return Context.Outbox.ToList();
        }

        public override IQueryable<Outbox> Query(System.Linq.Expressions.Expression<Func<Outbox, bool>> filter)
        {

            //var query  = Context.Outbox.Where(filter).OrderBy(x => x.OutboxNo);
            //var sql = ((ObjectQuery)query).ToTraceString();
            //Console.WriteLine(sql);
            //return query;
            return Context.Outbox.Where(filter).OrderBy(x => x.OutboxNo);
        }
        //ToDo: Document any exception might be thrown.
        /// <summary>
        /// Persists all updates to the data source and resets change tracking in the
        /// object context.
        /// </summary>
        /// <exception cref="DataModelException"/>
        public override void Save()
        {
            //ToDo: Impelement last step validation if required.
            try
            {
                base.Save();
            }
            catch (UpdateException ex)
            {
                string msg = Properties.Resources.PrimaryKeyDuplicateMsg;

                throw new DataModelException(msg, ex);

            }
            catch(Exception ex)
            {
                throw new DataModelException(ex.Message, ex);
            }
            
        }
        /// <summary>
        /// Refresh the whole Outbox entities in the Context, so there state will reset to Unchanged.<para/>
        /// <remarks>
        ///  This method will reset the state of any entity in the Context From <para/>
        ///  Modified, Deleted or Added to Unchanged only if that entity exist in datastoe.<para/>
        ///  If you try to refesh any entity that does exit in the Context but not yet <para/> submeted to datastore
        /// the state of that entity will remain as it's before refresh.<para/>
        /// Instead if you want to untrack that entity consider remove <para/>
        /// that entity entirely from the Context.
        /// </remarks>
        /// </summary>
        public override void RefreshContext()
        {
            Context.Refresh(System.Data.Objects.RefreshMode.StoreWins, Context.Outbox);
        }
        public static int GenerateOutboxNo(string activeYear)
        {
            string maxNo = Outbox.MaxOutboxNo();
            if (maxNo != null)
            {
                string yearPortion = maxNo.Substring(0, 4);
                if (yearPortion.Equals(activeYear))
                {
                    int incrementedNo;
                    if (int.TryParse(maxNo, out incrementedNo))
                    {
                        incrementedNo++;
                    }
                    return incrementedNo;
                }
            }
            return Helper.StartNewIncrement(activeYear);
        }
        public bool TryFindOutbox(string outboxNo, string currentYear, out Outbox outbox)
        {
            bool result = false;
            string s =  Helper.ApplayOutboxNoPattern(outboxNo, currentYear);
            try
            {
                outbox = GetByID(s);
            }
            catch
            {
                outbox = null;
            }
            if (outbox != null)
            {
                result =true;
            }
            else
            {
                result = false;
            }
            return result;

        }
        
        
    }
}
